package com.bw.demo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.utils.MyKafkaUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternFlatSelectFunction;
import org.apache.flink.cep.PatternFlatTimeoutFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.List;
import java.util.Map;

/**
 * @ClassName Demo2
 * @Description TODO
 * @Author SXLWTT 单新龙
 * @Date 2022/4
 * @Version 1.0
 **/
public class Demo2 {

    public static void main(String[] args) throws Exception {

        //1）获取kafka中的页面数据（5分）
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
//        env.enableCheckpointing(10000);
//        env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
        //new ProducerRecord<>(sink_table, data.toString().getBytes())
//        env.setStateBackend(new FsStateBackend("hdfs://hadoop102:8020/"));
        String topic ="dwd_page_log";
        String groupId ="Sxl01";
        //2）把数据流格式转换成json格式并输出。（5分）
        FlinkKafkaConsumer<String> kafkaSource = MyKafkaUtil.getKafkaSource(topic, groupId);
        kafkaSource.setStartFromEarliest();
        DataStreamSource<String> stringDataStreamSource = env.addSource(kafkaSource);
        //转JSON格式
        SingleOutputStreamOperator<JSONObject> map = stringDataStreamSource.map(json -> JSON.parseObject(json));
        //map.print("把数据流格式转换成json格式并输出");

        //
        //3)通过 Flink 的 CEP 完成页面跳出判断。（5分）
        //设置水位线
        SingleOutputStreamOperator<JSONObject> ts = map.assignTimestampsAndWatermarks(
                WatermarkStrategy.<JSONObject>forMonotonousTimestamps()
                        .withTimestampAssigner(
                                new SerializableTimestampAssigner<JSONObject>() {
                                    @Override
                                    public long extractTimestamp(JSONObject jsonObject, long l) {
                                        return jsonObject.getLong("ts");
                                    }
                                }
                        )
        );
        //根据mid分组
        KeyedStream<JSONObject, String> json = ts.keyBy(
                jsonObject -> jsonObject.getJSONObject("common").getString("mid")
        );
        //定义CEP规则
        Pattern<JSONObject, JSONObject> within = Pattern.<JSONObject>begin("first")
                .where(
                        //第一次判断
                        new SimpleCondition<JSONObject>() {
                            @Override
                            public boolean filter(JSONObject jsonObject) throws Exception {
                                //获取首次登录的ID
                                String string = jsonObject.getJSONObject("page").getString("last_page_id");
                                if (string == null || string.length() == 0) {
                                    return true;
                                }else {
                                    return false;
                                }

                            }
                        }
                ).next("next")//严格紧邻
                .where(
                        //第二次判断
                        new SimpleCondition<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject jsonObject) throws Exception {
                        //获取page_id
                        String string = jsonObject.getJSONObject("page").getString("page_id");
                        if (string !=null || string.length()>0){
                            return true;
                        }else {
                            return false;
                        }

                    }
                })
                //处理时间
                .within(Time.milliseconds(10000));
        //放入CEP规则里
        PatternStream<JSONObject> pattern = CEP.pattern(json, within);

        OutputTag<String> timeOut = new OutputTag<String>("timeOut"){};
        SingleOutputStreamOperator<Object> first = pattern.flatSelect(
                timeOut,
                new PatternFlatTimeoutFunction<JSONObject, String>() {
                    @Override
                    public void timeout(Map<String, List<JSONObject>> map, long l, Collector<String> collector) throws Exception {
                        List<JSONObject> first = map.get("first");
                        for (JSONObject jsonObject : first) {
                            collector.collect(jsonObject.toJSONString());
                        }
                    }
                },
                new PatternFlatSelectFunction<JSONObject, Object>() {
                    @Override
                    public void flatSelect(Map<String, List<JSONObject>> map, Collector<Object> collector) throws Exception {
                            //这里我们不需要判断
                    }
                }
        );
        DataStream<String> sideOutput = first.getSideOutput(timeOut);
        sideOutput.print("超时数据》》跳出判断>>");
        env.execute();
    }
}
